<template>
  <div class="update-photo">
    <img class="img" :src="img" ref="img" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data() {
    return {}
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    const image = this.$refs.img
    const cropper = new Cropper(image, {
      viewMode: 1, // 查看模式 0:裁剪框可以延伸到画布之外;1:限制裁剪框不超过画布的大小
      dragMode: 'move', // 拖动模式 crop:创建一个新的裁剪框; move: 移动画布,图片移动；none：移动裁剪框
      aspectRatio: 1, // 裁剪比例 默认16/9
      autoCropArea: 1, // 自动截取区域
      cropBoxMovable: false, // 截图区域是否可以移动
      cropBoxResizable: false, // 截图区域缩放
      background: false, // 背景
      movable: true
      // crop(event) {
      //   console.log(event.detail.x)
      //   console.log(event.detail.y)
      //   console.log(event.detail.width)
      //   console.log(event.detail.height)
      //   console.log(event.detail.rotate)
      //   console.log(event.detail.scaleX)
      //   console.log(event.detail.scaleY)
      // }
    })
    console.log(cropper)
  },
  methods: {
    onConfirm() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        const fomData = new FormData()
        fomData.append('photo', blob)
        const { data } = await updateUserPhoto(fomData)
        this.$emit('close')
        this.$emit('updata-photo', data.data.photo)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
